import React, { useState, useEffect } from 'react';
import { Tree, Table, Button, message } from 'antd';
import _ from 'lodash';
import styles from '../FlowLayout/index.less';
import * as apis from '@/services/SystemMgr';
import Eject from '@/components/Eject';
import Edit from './Edit';

const { TreeNode } = Tree;
const MonitoringStandard = () => {
  const [treeData, setTreeData] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [rowData, setRowData] = useState(null);
  const [orgId, setOrgId] = useState([]);
  const [orgName, setOrgName] = useState('');
  const [params, setParams] = useState(null);
  const [loading, setLoading] = useState(true);

  // 请求表格数据 --- Begin
  const requestTableData = arrOrgId => {
    setLoading(true);
    if (_.isEmpty(arrOrgId)) {
      return setLoading(false);
    }
    apis.getMonitorConfigDetailListUsingGET({ params: { orgId: arrOrgId[0] } }).then(result => {
      if (result && result.code === 1 && !_.isEmpty(result.data)) {
        const initTableData = result.data;
        const cloneTableData = _.cloneDeep(_.unionBy(initTableData, 'targetName'));
        _.each(cloneTableData, item => {
          const x = item;
          x.rowSpan = 0;
        });
        // 储
        const store = _.filter(cloneTableData, v => v.dimensionName === '储');
        store[0].rowSpan = store.length;
        // 产
        const produce = _.filter(cloneTableData, v => v.dimensionName === '产');
        produce[0].rowSpan = produce.length;
        // 供
        const supply = _.filter(cloneTableData, v => v.dimensionName === '供');
        supply[0].rowSpan = supply.length;
        // 销
        const sale = _.filter(cloneTableData, v => v.dimensionName === '销');
        sale[0].rowSpan = sale.length;
        // 存
        const deposit = _.filter(cloneTableData, v => v.dimensionName === '存');
        deposit[0].rowSpan = deposit.length;
        // 结
        const junction = _.filter(cloneTableData, v => v.dimensionName === '结');
        junction[0].rowSpan = junction.length;
        const concatTableData = _.concat(store, produce, supply, sale, deposit, junction);
        setDataSource(concatTableData);
      } else {
        setDataSource([]);
      }
      setLoading(false);
    });
  };
  // 请求表格数据 --- End
  useEffect(() => {
    apis
      .getOrgTreeUsingGET({
        params: {},
      })
      .then(result => {
        if (result && result.code === 1) {
          const orgname = result.data[0].orgnamefullpath.split('-')[1];
          setOrgName(orgname);
          setOrgId([result.data[0].parentOrgid]);
          setTreeData(result.data);
          requestTableData([result.data[0].parentOrgid]);
        }
      });
  }, []);
  // 点击组织架构数获取id --- End

  const columns = [
    {
      title: '序号',
      width: '7%',
      align: 'center',
      dataIndex: 'index',
      render: (text, row, index) => index + 1,
    },
    {
      title: '维度',
      width: '7%',
      dataIndex: 'dimensionName',
      align: 'center',
      render: (val, row) => {
        const obj = {
          children: val,
          props: {},
        };
        if (row.rowSpan > 0) {
          obj.props.rowSpan = row.rowSpan;
        } else {
          obj.props.rowSpan = 0;
        }
        return obj;
      },
    },
    {
      title: '指标名称',
      dataIndex: 'targetName',
      align: 'center',
      render: (val, row) => {
        let element = val;
        const condition =
          row.targetCode === 'c' ||
          row.targetCode === 'd' ||
          row.targetCode === 'l' ||
          row.targetCode === 'o' ||
          row.targetCode === 'p';
        if (condition) {
          element = (
            <Button
              type="link"
              onClick={() => {
                setRowData(null);
                setVisible(true);
                setRowData(row);
              }}
            >
              {val}
            </Button>
          );
        }
        return element;
      },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      width: '7%',
      align: 'center',
    },
    {
      title: '健康标准',
      dataIndex: 'healthStandard',
      align: 'center',
    },
    {
      title: '提醒标准',
      dataIndex: 'remindStandard',
      align: 'center',
    },
    {
      title: '预警标准',
      dataIndex: 'earlyWarningStandard',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
  ];
  const tableHeight = document.body.clientHeight - 215;
  const handleOkBtnClick = () => {
    apis
      .updateMonitorConfigDetailUsingPUT({
        data: params,
      })
      .then(result => {
        if (result && result.code === 1) {
          setDataSource([]);
          requestTableData(orgId);
          setVisible(false);
          message.success(result.message);
        }
      });
  };

  return (
    <div className={styles.FlowLayout}>
      <div className={styles.left}>
        {treeData && treeData.length > 0 ? (
          <Tree
            defaultExpandAll
            onSelect={selectedKeys => {
              setDataSource([]);
              setOrgId(selectedKeys);
              requestTableData(selectedKeys);
            }}
            defaultSelectedKeys={orgId}
          >
            <TreeNode key={treeData[0].parentOrgid} title={orgName}>
              {treeData.map(item => (
                <TreeNode key={item.orgdepid} title={item.orgname} />
              ))}
            </TreeNode>
          </Tree>
        ) : null}
      </div>
      <div className={styles.right}>
        <Table
          rowKey="targetName"
          loading={loading}
          scroll={{ y: tableHeight }}
          columns={columns}
          dataSource={dataSource}
          bordered
          pagination={false}
        />
      </div>
      {visible ? (
        <Eject
          title="编辑监控指标标准"
          width={500}
          handleOkBtnClick={handleOkBtnClick}
          onClose={() => setVisible(false)}
          visible={visible}
          modelJsx={<Edit rowData={rowData} orgId={orgId[0]} params={p => setParams(p)} />}
        />
      ) : null}
    </div>
  );
};

export default MonitoringStandard;
